//
// Created by forec on 17-5-1.
//

#include "../include/utils.h"

void nano_sleep(uint64_t ns){
    struct timespec ts;
    ts.tv_sec = 0; ts.tv_nsec = ns;
    nanosleep(&ts, 0);
}

bool isInitialBallot(int32_t ballot) {
    return (ballot >> 4) == 0;
}

bool equal(std::array<int32_t, GROUP_SIZE> & deps1,
           std::array<int32_t, GROUP_SIZE> & deps2) {
    for (int i = 0; i < deps1.size(); i++) {
        if (deps1[i] != deps2[i])
            return false;
    }
    return true;
}

bool ValidatePort(const char* flagname, int32_t value) {
    if (value > 0 && value < 32768)
        return true;
    printf("Invalid value for --%s: %d\n", flagname, (int)value);
    return false;
}

bool ValidateN(const char* flagname, int32_t value) {
    if (value >= 3 && value <= 13 && value % 2 == 1)
        return true;
    printf("Invalid value for --%s: %d\n", flagname, (int)value);
    return false;
}

bool ValidatePercent(const char* flagname, int32_t value) {
    if (value >= 0 && value <= 100)
        return true;
    printf("Invalid value for --%s: %d\n", flagname, (int)value);
    return false;
}

bool ValidateSize(const char* flagname, int32_t value) {
    if (value >= 0)
        return true;
    printf("Invalid value for --%s: %d\n", flagname, (int)value);
    return false;
}

std::string randStr(int least, int most) {
    if (most < least)
        most = least;
    int size = most > least ? least + (rand() % (most - least)) : most;
    std::string res((unsigned long)size, 'A');
    for (int i = 0; i < size; i++) {
        res[i] += rand() % 26;
    }
    return res;
}

int32_t randRange(int32_t least, int32_t most) {
    if (most <= least)
        return least;
    return (rand() % (most - least)) + least;
}


uint32_t ch_to_int32(unsigned char* buf){
    uint32_t ret =  (buf[0] <<  24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
    return ret;
}

unsigned char * int32_to_ch(uint32_t num){

    unsigned char *ret = (unsigned char *)malloc(sizeof(unsigned char) * 4);
    ret[0] = num >> 24;
    ret[1] = num >> 16;
    ret[2] = num >> 8;
    ret[3] = num;
    return ret;

}